import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
// 管理员后台页面统一迁移到 admin 目录
import DepartmentView from '@/views/admin/DepartmentView.vue'
import MajorView from '@/views/admin/MajorView.vue'
import ClassView from '@/views/admin/ClassView.vue'
import StudentView from '@/views/admin/StudentView.vue'
import TeacherView from '@/views/admin/TeacherView.vue'
import CourseView from '@/views/admin/CourseView.vue'
import CourseSelectionView from '@/views/admin/CourseSelectionView.vue'
// 管理员单独 Dashboard 已合并进统一 RoleDashboard，这里仍保留 admin 路由如需要
import AdminDashboard from '@/views/admin/AdminDashboard.vue'
import AdminView from '@/views/admin/AdminView.vue'
import { loginStatus } from '@/api'
import store from '@/store'
// 动态/懒加载学生扩展页面
const CourseSelectionStudent = () => import('@/views/student/CourseSelectionStudent.vue')
const StudentCourses = () => import('@/views/student/StudentCoursesView.vue')
const StudentTimetable = () => import('@/views/student/StudentTimetableView.vue')
const StudentGrades = () => import('@/views/student/StudentGradesView.vue')
const StudentProfile = () => import('@/views/student/StudentProfileView.vue')
// 教师端懒加载页面
const TeacherTimetable = () => import('@/views/teacher/TeacherTimetable.vue')
const TeacherGradeEntry = () => import('@/views/teacher/TeacherGradeEntry.vue')
const TeacherCourseList = () => import('@/views/teacher/TeacherCourseList.vue')


Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    component: HomeView,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import('@/views/RoleDashboard.vue')
      },
      {
        path: 'department',
        name: 'department',
        component: DepartmentView,
        meta: { requiredPermission: 'dept', adminOnly: true }
      },
      {
        path: 'major',
        name: 'major',
        component: MajorView,
        meta: { requiredPermission: 'major', adminOnly: true }
      },
      {
        path: 'class',
        name: 'class',
        component: ClassView,
        meta: { requiredPermission: 'class' }
      },
      {
        path: 'student',
        name: 'student',
        component: StudentView,
        meta: { requiredPermission: 'student' }
      },
      {
        path: 'teacher',
        name: 'teacher',
        component: TeacherView,
        meta: { requiredPermission: 'teacher', adminOnly: true }
      },
      {
        path: 'course',
        name: 'course',
        component: CourseView,
        meta: { requiredPermission: 'course' }
      },
      {
        path: 'course-selection',
        name: 'courseSelection',
        component: CourseSelectionView,
        meta: { requiredPermission: 'courseSelection', adminOnly: true }
      },
      // ===== 学生自助功能（基于 userType=1，非后台权限位） =====
      { path: 'elective-courses', name: 'studentElectiveCourses', component: CourseSelectionStudent, meta: { studentOnly: true } },
      { path: 'student-courses', name: 'studentCourses', component: StudentCourses, meta: { studentOnly: true } },
      { path: 'student-timetable', name: 'studentTimetable', component: StudentTimetable, meta: { studentOnly: true } },
      { path: 'student-grades', name: 'studentGrades', component: StudentGrades, meta: { studentOnly: true } },
      { path: 'student-profile', name: 'studentProfile', component: StudentProfile, meta: { studentOnly: true } },
      // ===== 教师自助功能（基于 userType=2） =====
      { path: 'teacher-timetable', name: 'teacherTimetable', component: TeacherTimetable, meta: { teacherOnly: true } },
      { path: 'teacher-grade-entry', name: 'teacherGradeEntry', component: TeacherGradeEntry, meta: { teacherOnly: true } },
      { path: 'teacher-courses', name: 'teacherCourses', component: TeacherCourseList, meta: { teacherOnly: true } },
      {
        path: 'admin',
        name: 'admin',
        component: () => import('@/views/admin/AdminDashboard.vue'),
        meta: { requiredPermission: 'admin', adminOnly: true }
      },
      {
        path: 'admin-manage',
        name: 'adminManage',
        component: AdminView,
        meta: { requiredPermission: 'admin', adminOnly: true }
      }
    ]
  },
  // 兼容旧路径
  {
    path: '/Home',
    redirect: '/home'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  console.log('Router guard - navigating to:', to.path)
  const loggedIn = store.state.user.loggedIn
  const userType = store.state.user.userType
  const permissions = store.state.user.permissions || []
  const reqPerm = to.meta && to.meta.requiredPermission
  const adminOnly = to.meta && to.meta.adminOnly
  const studentOnly = to.meta && to.meta.studentOnly
  const teacherOnly = to.meta && to.meta.teacherOnly
  const studentAccessible = to.meta && to.meta.studentAccessible
  const isAdmin = userType === 3

  const allowRoleOnly = () => {
    if (studentOnly && userType !== 1) return false
    if (teacherOnly && userType !== 2) return false
    return true
  }

  const checkPerm = () => {
  if (!allowRoleOnly()) return false
    if (adminOnly && !isAdmin) return false
    if (reqPerm) {
      // 学生访问加了 studentAccessible 的路由时放行
      if (userType === 1 && studentAccessible) return true
      if (permissions.length === 0 && isAdmin) return true // 管理员空权限兜底
      if (!permissions.includes(reqPerm) && !isAdmin) return false
    }
    return true
  }

  const proceed = () => {
    if (!checkPerm()) return next('/home')
    next()
  }

  if (loggedIn) {
    if (to.path === '/login') return next('/home')
    return proceed()
  }
  try {
    const ret = await loginStatus()
    if (ret.data.loggedIn) {
      store.commit('user/updateloggedIn', ret.data)
      return proceed()
    }
    if (to.path === '/login') return next()
    return next('/login')
  } catch (e) {
    if (to.path === '/login') return next()
    return next('/login')
  }
})

// 处理重复导航（如快速点击菜单）产生的 NavigationDuplicated 警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => {
    if (err && err.name === 'NavigationDuplicated') return err
    throw err
  })
}

export default router
